package com.bci.pwtz.controller.app;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bci.pwtz.common.PwtzConstants;
import com.bci.pwtz.common.remote.BaseResponse;
import com.bci.pwtz.common.remote.ListResponse;
import com.bci.pwtz.common.remote.ObjResponse;
import com.bci.pwtz.common.remote.ReturnCode;
import com.bci.pwtz.common.remote.req.KzsxsbzpDelReq;
import com.bci.pwtz.common.remote.req.KzsxsbzpListReq;
import com.bci.pwtz.common.remote.req.KzsxsbzpReq;
import com.bci.pwtz.common.util.FileUtils;
import com.bci.pwtz.common.util.PaginationList;
import com.bci.pwtz.common.util.PwtzUtils;
import com.bci.pwtz.controller.AbstractController;
import com.bci.pwtz.exception.CanNotDeleteException;
import com.bci.pwtz.exception.PwtzDatabaseException;
import com.bci.pwtz.mysql.dao.ConfigMapper;
import com.bci.pwtz.mysql.model.Config;
import com.bci.pwtz.mysql.model.Kzsxsbzp;
import com.bci.pwtz.service.KzsxsbzpService;
import com.bci.pwtz.service.PictureUploadAndDownloadService;
@Controller
@RequestMapping("/api/kzsxsbzp")
public class KzsxsbzpAppController extends AbstractController
{
@Autowired
KzsxsbzpService service;
@Autowired
PictureUploadAndDownloadService picture;
@Autowired
ConfigMapper configMapper;
/**
 * 反孤岛装置的list查询
 * 一句话描述 <br/>
 * <p>Description: TODO(详细描述) 
 * <br/>
 * <p>Author: Administrator<br/>
 * <p>Date: 2014年9月25日-上午10:25:21<br/>
 * <p>
 * @param request
 * @return   
 *
 */
@RequestMapping(value = "/list", method = RequestMethod.POST)
@ResponseBody
public ListResponse<Kzsxsbzp> list(HttpServletRequest request)
{
    KzsxsbzpListReq req = null;
    ListResponse<Kzsxsbzp> resp = new ListResponse<Kzsxsbzp>();
    PaginationList<Kzsxsbzp> list = new PaginationList<Kzsxsbzp>();
    try
    {
        req =getJsonToObj(request, KzsxsbzpListReq.class);
        if (req == null)
        {
            resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
            resp.setReturnMsg("请求为空");
            return resp;
        }
        if( req.getTimestamp() == null){
            resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
            resp.setReturnMsg("时间戳为空");
            resp.setTimestamp(req.getTimestamp());
            return resp;  
        }
        if (req.getSecretKey() == null)
        {
            resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
            resp.setReturnMsg("密钥为空");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        if(req.getCompanyId()==null){
            resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
            resp.setReturnMsg("参数错误");
            resp.setTimestamp(req.getTimestamp());
            return resp; 
        }
        if (!validateSecretKey(req.getSecretKey(), req.getTimestamp()))
        {
            resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
            resp.setReturnMsg("密钥错误");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        if (req.getUserId() == null)
        {
            resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
            resp.setReturnMsg("用户ID为空");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        if (StringUtils.isBlank(req.getToken()) || !validateToken(req.getToken(), req.getUserId()))
        {
            resp.setReturnCode(ReturnCode.TOKEN_INVALID);
            resp.setReturnMsg("票据无效");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        list=service.findKzsxsbzp(req.getCompanyId(),PwtzConstants.PORTAL_TYPE_APP,req.getMedLineCodes(), req.getBeginTime(), null, req.getPageSize(),req.getPage());
        if (list != null)
        {
            resp.setReturnCode(ReturnCode.SUCCESS);
            resp.setReturnMsg("查询扩展属性设备照片列表信息成功");
//            if(list.getRecords().size()>0){
//                Config config=configMapper.selectByKey("DevicePICPath").get(0);
//                String configpath=config.getConfigValue().replaceAll("@COMPANYID", list.getRecords().get(0).getCompanyid().toString());
//                String host=configMapper.selectByKey("DevicePicHost").get(0).getConfigValue();
//                String port=configMapper.selectByKey("DevicePicPort").get(0).getConfigValue();
//                String userName=configMapper.selectByKey("FtpUserName").get(0).getConfigValue();
//                String userPassword=configMapper.selectByKey("FtpUserPassword").get(0).getConfigValue();
//                String remotePath=configMapper.selectByKey("FtpPicPath").get(0).getConfigValue();
//                //String configpath="D:\\";
//                for(Kzsxsbzp k:list.getRecords()){
//                    //k.setImagestring(picture.download(configpath, k.getPhotoname()));;
//                    //String test=picture.download(configpath, k.getPhotoname());
//                    //k.setSmallimagestring(picture.download(configpath, k.getPhotoname().replaceAll(".", "small.")));;
//                    //picture.upload(test, "E:\\", k.getPhotoname());
//                    FileUtils.ftpUpload(host, port, userName, userPassword, remotePath, configpath, k.getPhotoname());
//                }
//            }
            resp.setTimestamp(req.getTimestamp());
            resp.setObjs(list);
        }else{
            resp.setReturnCode(ReturnCode.INTERFACE_INVOKE_ERROR);
            resp.setReturnMsg("查询扩展属性设备照片列表信息调用接口返回失败");
            resp.setTimestamp(req.getTimestamp());
        }
    }
    catch (PwtzDatabaseException e)
    {
        resp.setReturnCode(ReturnCode.DB_EXCEPTION);
        resp.setReturnMsg("数据库操作异常");
        resp.setTimestamp(req.getTimestamp());
    }
    catch (Exception e)
    {
        resp.setReturnCode(ReturnCode.UNKOWN_ERROR);
        resp.setReturnMsg("系统错误");
        resp.setTimestamp(req.getTimestamp());
    }
    return resp;
}

/**
 * 新增反孤岛装置信息
 * 一句话描述 <br/>
 * <p>Description: TODO(详细描述) 
 * <br/>
 * <p>Author: Administrator<br/>
 * <p>Date: 2014年9月25日-上午10:25:38<br/>
 * <p>
 * @param request
 * @return   
 *
 */
@RequestMapping(value = "/add", method = RequestMethod.POST)
@ResponseBody
public ObjResponse<Kzsxsbzp> add(HttpServletRequest request)
{
    ObjResponse<Kzsxsbzp> resp = new ObjResponse<Kzsxsbzp>();
    KzsxsbzpReq req = null;
    try
    {
        req = (KzsxsbzpReq) getJsonToObj(request, KzsxsbzpReq.class);
        if (req == null)
        {
            resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
            resp.setReturnMsg("请求为空");
            return resp;
        }
        if(req.getTimestamp() == null){
            resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
            resp.setReturnMsg("时间戳为空");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        if (req.getSecretKey() == null)
        {
            resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
            resp.setReturnMsg("密钥为空");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        if (!validateSecretKey(req.getSecretKey(), req.getTimestamp()))
        {
            resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
            resp.setReturnMsg("密钥错误");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        if (req.getUserId() == null)
        {
            resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
            resp.setReturnMsg("用户ID为空");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        if (StringUtils.isBlank(req.getToken()) || !validateToken(req.getToken(), req.getUserId()))
        {
            resp.setReturnCode(ReturnCode.TOKEN_INVALID);
            resp.setReturnMsg("票据无效");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        Kzsxsbzp obj =req.getObj();
        Config config=configMapper.selectByKey("DevicePICPath").get(0);
        String configpath=config.getConfigValue().replaceAll("@COMPANYID", obj.getCompanyid()+"");
        String host=configMapper.selectByKey("DevicePicHost").get(0).getConfigValue();
        String port=configMapper.selectByKey("DevicePicPort").get(0).getConfigValue();
        String userName=configMapper.selectByKey("FtpUserName").get(0).getConfigValue();
        String userPassword=configMapper.selectByKey("FtpUserPassword").get(0).getConfigValue();
        String remotePath=configMapper.selectByKey("FtpPicPath").get(0).getConfigValue();
        boolean result=FileUtils.ftpDownload(host, PwtzUtils.passInt(port), userName, userPassword,remotePath, obj.getPhotoname(), configpath);
        if(result){
            obj=service.add(obj);
            if (obj != null)
            {
                resp.setReturnCode(ReturnCode.SUCCESS);
                resp.setReturnMsg("新增扩展设备属性照片成功");
                resp.setTimestamp(req.getTimestamp());
                //String configpath="D:\\";
                
                //System.out.println(result);
                setLog(obj.getDeviceid(), obj.getCompanyid(), 0, AbstractController.add, "新增扩展属性设备照片["+obj.getPhotoname()+"]成功", req.getUserId());
                resp.setObj(obj);
            }else{
                resp.setReturnCode(ReturnCode.INTERFACE_INVOKE_ERROR);
                resp.setReturnMsg("新增扩展设备属性照片调用接口返回失败");
                resp.setTimestamp(req.getTimestamp());
            }
        }else{
            resp.setReturnCode(ReturnCode.INTERFACE_INVOKE_ERROR);
            resp.setReturnMsg("获取上传图片失败");
            resp.setTimestamp(req.getTimestamp());
        }
    }
    catch (PwtzDatabaseException e)
    {
        resp.setReturnCode(ReturnCode.DB_EXCEPTION);
        resp.setReturnMsg("数据库操作异常");
        resp.setTimestamp(req.getTimestamp());
    }
    catch (Exception e)
    {
        resp.setReturnCode(ReturnCode.UNKOWN_ERROR);
        resp.setReturnMsg("系统错误");
        resp.setTimestamp(req.getTimestamp());
    }
    return resp;
}

/**
 * 修改反孤岛装置信息
 * 一句话描述 <br/>
 * <p>Description: TODO(详细描述) 
 * <br/>
 * <p>Author: Administrator<br/>
 * <p>Date: 2014年9月25日-上午10:25:55<br/>
 * <p>
 * @param request
 * @return   
 *
 */
@RequestMapping(value = "/update", method = RequestMethod.POST)
@ResponseBody
public ObjResponse<Kzsxsbzp> update(HttpServletRequest request)
{
    ObjResponse<Kzsxsbzp> resp = new ObjResponse<Kzsxsbzp>();
    KzsxsbzpReq req = null;
    int result = 0;
    try
    {
        req = (KzsxsbzpReq) getJsonToObj(request, KzsxsbzpReq.class);
        if (req == null)
        {
            resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
            resp.setReturnMsg("请求为空");
            return resp;
        }
        if( req.getTimestamp() == null){
            resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
            resp.setReturnMsg("时间戳为空");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        if(req.getObj()==null){
            resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
            resp.setReturnMsg("参数错误");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        if (req.getSecretKey() == null)
        {
            resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
            resp.setReturnMsg("密钥为空");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        if (!validateSecretKey(req.getSecretKey(), req.getTimestamp()))
        {
            resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
            resp.setReturnMsg("密钥错误");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        if (req.getUserId() == null)
        {
            resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
            resp.setReturnMsg("用户ID为空");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        if (StringUtils.isBlank(req.getToken()) || !validateToken(req.getToken(), req.getUserId()))
        {
            resp.setReturnCode(ReturnCode.TOKEN_INVALID);
            resp.setReturnMsg("票据无效");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        result = service.update(req.getObj());
        if (result > 0)
        {
            resp.setReturnCode(ReturnCode.SUCCESS);
            resp.setReturnMsg("修改扩展属性设备照片成功");
            if(req.getObj().getImagestring()!=null&&req.getObj().getImagestring()!=""){
                Config config=configMapper.selectByKey("DevicePICPath").get(0);
                String configpath=config.getConfigValue().replaceAll("@COMPANYID", req.getObj().getCompanyid().toString());
//                picture.upload(req.getObj().getImagestring(), configpath, req.getObj().getPhotoname());
//                picture.upload(req.getObj().getSmallimagestring(), configpath, req.getObj().getPhotoname().replaceAll(".", "small."));
            }
            resp.setTimestamp(req.getTimestamp());
            resp.setObj(req.getObj());
            setLog(req.getObj().getDeviceid(), req.getObj().getCompanyid(), 0, AbstractController.update, "修改扩展属性设备照片["+req.getObj().getPhotoname()+"]成功", req.getUserId());
        }else{
            resp.setReturnCode(ReturnCode.INTERFACE_INVOKE_ERROR);
            resp.setReturnMsg("修改扩展属性设备照片调用接口返回失败");
            resp.setTimestamp(req.getTimestamp());
        }
    }
    catch (PwtzDatabaseException e)
    {
        resp.setReturnCode(ReturnCode.DB_EXCEPTION);
        resp.setReturnMsg("数据库操作异常");
        resp.setTimestamp(req.getTimestamp());
    }
    catch (Exception e)
    {
        resp.setReturnCode(ReturnCode.UNKOWN_ERROR);
        resp.setReturnMsg("系统错误");
        resp.setTimestamp(req.getTimestamp());
    }
    return resp;
}

/**
 * 删除反孤岛装置信息
 * 一句话描述 <br/>
 * <p>Description: TODO(详细描述) 
 * <br/>
 * <p>Author: Administrator<br/>
 * <p>Date: 2014年9月25日-上午10:26:15<br/>
 * <p>
 * @param request
 * @return   
 *
 */
@RequestMapping(value = "/delete", method = RequestMethod.POST)
@ResponseBody
public ObjResponse<Kzsxsbzp> delete(HttpServletRequest request)
{
    ObjResponse<Kzsxsbzp> resp = new ObjResponse<Kzsxsbzp>();
    KzsxsbzpReq req = null;
    int result = 0;
    try
    {
        req = (KzsxsbzpReq) getJsonToObj(request, KzsxsbzpReq.class);
        if (req == null)
        {
            resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
            resp.setReturnMsg("请求为空");
            return resp;
        }
        if( req.getTimestamp() == null){
            resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
            resp.setReturnMsg("时间戳为空");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        if(req.getObj()==null){
            resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
            resp.setReturnMsg("参数错误");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        if (req.getSecretKey() == null)
        {
            resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
            resp.setReturnMsg("密钥为空");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        if (!validateSecretKey(req.getSecretKey(), req.getTimestamp()))
        {
            resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
            resp.setReturnMsg("密钥错误");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        if (req.getUserId() == null)
        {
            resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
            resp.setReturnMsg("用户ID为空");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        if (StringUtils.isBlank(req.getToken()) || !validateToken(req.getToken(), req.getUserId()))
        {
            resp.setReturnCode(ReturnCode.TOKEN_INVALID);
            resp.setReturnMsg("票据无效");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        Config config=configMapper.selectByKey("DevicePICPath").get(0);
        String configpath=config.getConfigValue().replaceAll("@COMPANYID", req.getObj().getCompanyid().toString());
        boolean flag=picture.delete(configpath, req.getObj().getPhotoname());
        if(flag){
            result = service.delete(req.getObj().getId());
            if (result > 0)
            {
                //Kzsxsbzp rtObj=service.load(req.getObj().getId());
                resp.setReturnCode(ReturnCode.SUCCESS);
                resp.setReturnMsg("删除扩展属性设备照片成功");
                resp.setTimestamp(req.getTimestamp());
                req.getObj().setStatus(3);
                resp.setObj(req.getObj());
                setLog(req.getObj().getId(), req.getObj().getCompanyid(), 0, AbstractController.delete, "删除扩展属性设备照片["+req.getObj().getPhotoname()+"]成功", req.getUserId());
            }else{
                resp.setReturnCode(ReturnCode.INTERFACE_INVOKE_ERROR);
                resp.setReturnMsg("删除扩展属性设备照片调用接口返回失败");
                resp.setTimestamp(req.getTimestamp());
            }
        }else{
            resp.setReturnCode(ReturnCode.INTERFACE_INVOKE_ERROR);
            resp.setReturnMsg("删除照片调用接口返回失败");
            resp.setTimestamp(req.getTimestamp()); 
        }
    }
    catch (CanNotDeleteException e)
    {
        resp.setReturnCode(ReturnCode.DB_EXCEPTION);
        resp.setReturnMsg("存在依耐关系，不能删除");
        resp.setTimestamp(req.getTimestamp());
    }
    catch (PwtzDatabaseException e)
    {
        resp.setReturnCode(ReturnCode.DB_EXCEPTION);
        resp.setReturnMsg("数据库操作异常");
        resp.setTimestamp(req.getTimestamp());
    }
    catch (Exception e)
    {
        resp.setReturnCode(ReturnCode.UNKOWN_ERROR);
        resp.setReturnMsg("系统错误");
        resp.setTimestamp(req.getTimestamp());
    }
    return resp;
}

@RequestMapping(value = "/deleteall", method = RequestMethod.POST)
@ResponseBody
public BaseResponse deleteAll(HttpServletRequest request)
{
    BaseResponse resp = new BaseResponse();
    KzsxsbzpDelReq req = null;
    try
    {
        req = (KzsxsbzpDelReq) getJsonToObj(request, KzsxsbzpDelReq.class);
        if (req == null)
        {
            resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
            resp.setReturnMsg("请求为空");
            return resp;
        }
        if( req.getTimestamp() == null){
            resp.setReturnCode(ReturnCode.PARAMETER_ERROR);
            resp.setReturnMsg("时间戳为空");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        if (req.getSecretKey() == null)
        {
            resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
            resp.setReturnMsg("密钥为空");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        if (!validateSecretKey(req.getSecretKey(), req.getTimestamp()))
        {
            resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
            resp.setReturnMsg("密钥错误");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        if (req.getUserId() == null)
        {
            resp.setReturnCode(ReturnCode.SECRET_KEY_ERROR);
            resp.setReturnMsg("用户ID为空");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        if (StringUtils.isBlank(req.getToken()) || !validateToken(req.getToken(), req.getUserId()))
        {
            resp.setReturnCode(ReturnCode.TOKEN_INVALID);
            resp.setReturnMsg("票据无效");
            resp.setTimestamp(req.getTimestamp());
            return resp;
        }
        List<Kzsxsbzp> list=service.selectDeviceList(req.getCompanyId(),req.getDeviceId());
        boolean result=true;
        if(list!=null&&list.size()>0){
            for(Kzsxsbzp k:list){
                if(k.getPhotoname()!=null&&k.getPhotoname()!=""){
                    Config config=configMapper.selectByKey("DevicePICPath").get(0);
                    String fileurl=config.getConfigValue().replaceAll("@COMPANYID", k.getCompanyid().toString());
                    //String fileurl="D:\\";
                    result=picture.delete(fileurl, k.getPhotoname());
                    if(!result){
                        break;
                    }
                    //picture.delete(fileurl, k.getPhotoname().replaceAll(".", "small."));
                }
                service.delete(k.getId());
            }
        }
        if (result)
        {
            resp.setReturnCode(ReturnCode.SUCCESS);
            resp.setReturnMsg("删除扩展属性设备照片成功");
            resp.setTimestamp(req.getTimestamp());
        }else{
            resp.setReturnCode(ReturnCode.INTERFACE_INVOKE_ERROR);
            resp.setReturnMsg("删除扩展属性设备照片调用接口返回失败");
            resp.setTimestamp(req.getTimestamp());
        }
    }
    catch (CanNotDeleteException e)
    {
        resp.setReturnCode(ReturnCode.DB_EXCEPTION);
        resp.setReturnMsg("存在依耐关系，不能删除");
        resp.setTimestamp(req.getTimestamp());
    }
    catch (PwtzDatabaseException e)
    {
        resp.setReturnCode(ReturnCode.DB_EXCEPTION);
        resp.setReturnMsg("数据库操作异常");
        resp.setTimestamp(req.getTimestamp());
    }
    catch (Exception e)
    {
        resp.setReturnCode(ReturnCode.UNKOWN_ERROR);
        resp.setReturnMsg("系统错误");
        resp.setTimestamp(req.getTimestamp());
    }
    return resp;
}
}
